package com.szl.group.config.auth.custom;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.szl.group.common.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.szl.group.common.enums.ResultCodeEnum.FORBIDDEN;

/**
 * 自定义403返回.
 * AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
 * 前后端分离中，需要返回json，而不是重定向，系统默认的重定向
 *
 * @author shenxiaolong
 * @date 2020/06/22  4:48 PM
 */
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse,
                         AuthenticationException e) throws IOException {

        httpServletResponse.setContentType("application/json;charset=UTF-8");

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(R
                        .builder()
                        .code(FORBIDDEN.getCode())
                        .message(FORBIDDEN.getMessage())
                        .build()));
    }
}
